package com.rico.kok.controller.post;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rico.kok.entity.Collection_;
import com.rico.kok.entity.Post;
import com.rico.kok.entity.User;
import com.rico.kok.entity.povos.PostUser;
import com.rico.kok.service.interf.CollectionService;
import com.rico.kok.service.interf.PostService;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
public class CollectionController {

    @Autowired
    CollectionService collectionService;

    @Autowired
    PostService postService;

    //收藏和取消收藏
    @RequiresRoles("user")
    @RequestMapping("/postCollection.htm")
    @ResponseBody
    public boolean collection(@RequestParam("id") String collectionPostId, HttpSession session){
        Post post = new Post();
        int userId = ((User) session.getAttribute("user")).getUserId();
        int i = Integer.parseInt(collectionPostId);
        post.setUserId(userId);
        post.setPostId(i);
        Integer isCollection = collectionService.isCollection(post);
        if (isCollection==null){
            collectionService.postCollection(post);
            return true;
        }else {
            collectionService.unCollection(post);
            return false;
        }
    }

    //获取收藏列表
    @RequiresRoles("user")
    @RequestMapping("/collectionList.htm")
    public String collectionList(@RequestParam(value = "num", defaultValue = "1") Integer pageNum,HttpSession session, Model model){
        User user = (User) session.getAttribute("user");
        if (user==null){
            return "login";
        }
        PageHelper.startPage(pageNum, 6,"collection_time desc");
        List<Collection_> collections = collectionService.collectionList(user.getUserId());
        PageInfo<PostUser> pageInfo=new PageInfo(collections);
        model.addAttribute("pageInfo",pageInfo);
        List<Integer> postIds=new ArrayList<>();
        for (Collection_ collection_:collections) {
            postIds.add(collection_.getPostId());
        }
        if (collections!=null&&collections.size()>0){
            List<PostUser> posts = postService.selectPostByPostIds(postIds);
            model.addAttribute("collections",posts);
        }
        return "collection_list";
    }
}
